<template>
  <div class="container">
    <topTitle
      :titleText="
        actionType === 'add' ? '创建专户拨付计划' : '修改专户拨付计划'
      "
      :back="true"
      @gobackTriser="goBack"
    ></topTitle>
    <!-- <el-row>
      <el-col class="topTitle">
        <i class="icon iconfont iconfanhui1" @click="goBack"></i>
        <span class="titleStyle">{{actionType==='add'?'创建专户拨付计划':'修改专户拨付计划'}}</span>
      </el-col>
    </el-row> -->
    <div class="mainCon">
      <el-row
        v-if="loginType == 'bulider' && payPlanType == 'MANUAL_NEED_AUDIT'"
        class="planProgress"
      >
        <div class="reminderBox">
          <ul class="reminder">
            <li>
              <span class="circle">1</span>
              <span class="titleInfo">施工方创建/修改拨付计划</span>
            </li>
            <li class="arrowRight">
              <img src="../../../static/img/icon2.png" alt />
            </li>
            <li>
              <span class="circle">2</span>
              <span class="titleInfo">建设方审核</span>
            </li>
            <li class="arrowRight">
              <img src="../../../static/img/icon2.png" alt />
            </li>
            <li>
              <span class="circle">3</span>
              <span class="titleInfo">审核通过后即可收到按时足额预警通知</span>
            </li>
          </ul>
        </div>
      </el-row>
      <div
        class="stateBox"
        v-if="payPlanType == 'MANUAL_NEED_AUDIT' && actionType == 'update'"
      >
        <el-row class="examineStatus">
          <el-row class="planStatus">
            <i
              class="iconfont iconyiqueren pass"
              v-if="projectDetail.auditStatus === 'PASSED'"
            ></i>
            <i
              class="iconfont icondengdai pending"
              v-if="projectDetail.auditStatus === 'WAIT_AUDIT'"
            ></i>
            <i
              class="iconfont iconshibai1 rejected"
              v-if="projectDetail.auditStatus === 'REJECTED'"
            ></i>
            <i
              class="iconfont iconshengming cancelling"
              v-if="projectDetail.auditStatus === 'WAIT_ABOLISH'"
            ></i>
            <i
              class="iconfont iconshibai1 cancelled"
              v-if="projectDetail.auditStatus === 'ABOLISHED'"
            ></i>
            <span style="margin-left: 14px">申报进度：</span>
            <span
              class="planStatus pass"
              v-if="projectDetail.auditStatus === 'PASSED'"
              >已通过</span
            >
            <span
              class="planStatus pending"
              v-if="projectDetail.auditStatus === 'WAIT_AUDIT'"
              >待审核</span
            >
            <span
              class="planStatus rejected"
              v-if="projectDetail.auditStatus === 'REJECTED'"
              >已驳回</span
            >
            <span
              class="planStatus cancelling"
              v-if="projectDetail.auditStatus === 'WAIT_ABOLISH'"
              >待作废</span
            >
            <span
              class="planStatus cancelled"
              v-if="projectDetail.auditStatus === 'ABOLISHED'"
              >已作废</span
            >
          </el-row>
          <el-row
            class="rejectedReason"
            v-if="projectDetail.auditStatus === 'REJECTED'"
          >
            <span v-if="projectDetail.rejectReason"
              >驳回原因：{{ projectDetail.rejectReason }}</span
            >
          </el-row>
        </el-row>
      </div>
      <div
        class="separator"
        v-if="payPlanType == 'MANUAL_NEED_AUDIT' && actionType == 'update'"
      ></div>
      <el-form
        :model="planFormData"
        :rules="rules"
        ref="planForm"
        label-width="100px"
      >
        <el-row class="contentInfo">
          <el-row>
            <el-col :span="24">
              <div class="secondaryTitle secondaryTitleTheme">专户信息</div>
            </el-col>
          </el-row>
          <el-row style="margin-top: 26px">
            <el-form-item
              label="项目名称："
              prop="projectId"
              style="margin-bottom: 0"
            >
              <el-select
                :disabled="actionType === 'update' ? true : false"
                v-model="planFormData.projectId"
                clearable
                @change="getProjectDetail(planFormData.projectId)"
                placeholder="请选择"
                class="dialogDoubleInp"
              >
                <el-option
                  v-for="item in projectList"
                  :label="item.name"
                  :value="item.code"
                  :key="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row class="detailInfoItemSty">
            <el-col :span="8">
              <span class="gridContent color333 fontSizeF rightBox"
                >施工方：</span
              >
              <span class="gridContent empContentSty color333 fontSizeF">{{
                projectDetail.pbName ? projectDetail.pbName : '--'
              }}</span>
            </el-col>
            <el-col :span="8">
              <span class="gridContent color333 fontSizeF">项目负责人：</span>
              <span class="gridContent empContentSty color333 fontSizeF">{{
                projectDetail.leader ? projectDetail.leader : '--'
              }}</span>
            </el-col>
            <el-col :span="8">
              <span class="gridContent color333 fontSizeF"
                >项目负责人电话：</span
              >
              <span class="gridContent empContentSty color333 fontSizeF">{{
                projectDetail.leaderTel ? projectDetail.leaderTel : '--'
              }}</span>
            </el-col>
          </el-row>
          <el-row class="detailInfoItemSty">
            <el-col :span="8">
              <span class="gridContent color333 fontSizeF rightBox"
                >建设方：</span
              >
              <span class="gridContent empContentSty color333 fontSizeF">{{
                projectDetail.pcName ? projectDetail.pcName : '--'
              }}</span>
            </el-col>
            <el-col :span="8">
              <span class="gridContent color333 fontSizeF">专户银行：</span>
              <span class="gridContent empContentSty color333 fontSizeF">{{
                projectDetail.bankName ? projectDetail.bankName : '--'
              }}</span>
            </el-col>
            <el-col :span="8">
              <span class="gridContent color333 fontSizeF">专户账号：</span>
              <span class="gridContent empContentSty color333 fontSizeF">{{
                projectDetail.account ? projectDetail.account : '--'
              }}</span>
            </el-col>
          </el-row>
        </el-row>
        <div class="separator"></div>
        <el-row class="contentInfo">
          <el-row style="margin-top: 20px; margin-bottom: 8px">
            <el-col :span="24">
              <div class="secondaryTitle secondaryTitleTheme">
                专户资金拨付计划
              </div>
            </el-col>
          </el-row>
          <el-row class="allocationDetail">
            <el-row class="detailInfoItemSty detailInfoItemSty32">
              <span class="gridContent color333 fontSizeF rightBox"
                >拨付周期：</span
              >
              <span class="gridContent empContentSty color333 fontSizeF"
                >按月拨付</span
              >
            </el-row>
            <el-row v-if="userType !== 'MONITOR'">
              <el-form-item
                label="应拨付总额："
                prop="total"
                v-if="projectDetail.calculateType === 'CONTRACT'"
              >
                <el-input
                  v-model="planFormData.total"
                  style="width: 120px"
                ></el-input
                >&nbsp;元
              </el-form-item>
              <el-row class="detailInfoItemSty detailInfoItemSty32" v-else>
                <span class="gridContent color333 fontSizeF rightBox"
                  >应拨付总额：</span
                >
                <span class="gridContent empContentSty color333 fontSizeF">
                  {{ planFormData.total }}元&ensp;（应拨付总额按照工程款*{{
                    projectDetail.scale
                  }}%来计算）
                  <!-- <span v-if="actionType===add">&ensp;（应拨付总额按照工程款*30%来计算）</span> -->
                </span>
              </el-row>
              <!-- <el-form-item label="应拨付总额" prop="total">
                <el-input
                  v-model="planFormData.total"
                  :disabled="true"
                  style="width:440px;background:none;border:none"
                >
                  <template slot="append">
                    <span>（应拨付总额按照工程款*30%来计算）</span>
                  </template>
                </el-input>
              </el-form-item>-->
            </el-row>
            <el-row class="detailInfoItemSty">
              <el-form-item
                label="拨付时间："
                prop="allocationTime"
                style="margin-bottom: 0"
              >
                <span>每月</span>
                <el-select
                  v-model="planFormData.allocationTime"
                  placeholder="请选择"
                  clearable
                  style="width: 120px"
                  @change="
                    getAllocationCircle('update', planFormData.allocationTime)
                  "
                >
                  <el-option
                    v-for="item in 31"
                    :label="item"
                    :value="item"
                    :key="item"
                  ></el-option>
                </el-select>
                <span>日前</span>
                <el-row class="empContentSty color333 fontSizeF"
                  >&ensp;（如设置29、30、31日，则不满29、30、31天的月份默认为当月最后一天）</el-row
                >
              </el-form-item>
            </el-row>
          </el-row>
          <el-row class="detailInfoItemSty">
            <span
              class="gridContent color333 fontSizeF"
              style="
                width: 100px;
                display: inline-block;
                vertical-align: top;
                padding-right: 10px;
                text-align: right;
              "
              >拨付计划：</span
            >
            <div style="display: inline-block; width: 80%">
              <el-table
                :data="planFormData.allocationPlan"
                id="allocationPlan"
                max-height="350px"
                border
                v-loading="isLoading"
                style="width: 960px; font-size: 14px; color: #333333"
              >
                <el-table-column label="拨付周期" align="center">
                  <template slot-scope="scope"
                    >{{ scope.row.startDate }}&nbsp;至&nbsp;{{
                      planFormData.allocationTime
                        ? scope.row.endDate
                        : '(请选择拨付时间)'
                    }}</template
                  >
                </el-table-column>
                <!-- 黄石定制需求 -->
                <el-table-column
                  label="本期应拨付"
                  align="center"
                  v-if="userType == 'MONITOR' && isHsUser()"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      style="
                        margin-bottom: 0;
                        width: 265px;
                        display: inline-block;
                      "
                      :prop="
                        'allocationPlan.' +
                        scope.$index +
                        '.shouldDisburseTotal'
                      "
                      :rules="rules.shouldDisburseTotal"
                      label-width="0"
                    >
                      <el-input
                        v-model="scope.row.shouldDisburseTotal"
                        @blur="checkLastCost('planForm', 'hs')"
                        style="width: 240px"
                        class="table-input"
                      ></el-input
                      >&ensp;元
                    </el-form-item>
                  </template>
                </el-table-column>
                <!-- 黄石定制需求 -->
                <el-table-column label="本期应拨付" align="center" v-else>
                  <template slot-scope="scope">
                    <el-form-item
                      v-if="
                        scope.$index < planFormData.allocationPlan.length - 1
                      "
                      style="
                        margin-bottom: 0;
                        width: 265px;
                        display: inline-block;
                      "
                      :prop="
                        'allocationPlan.' +
                        scope.$index +
                        '.shouldDisburseTotal'
                      "
                      :rules="rules.shouldDisburseTotal"
                      label-width="0"
                    >
                      <el-input
                        v-model="scope.row.shouldDisburseTotal"
                        @blur="checkLastCost('planForm', '')"
                        style="width: 240px"
                        class="table-input"
                      ></el-input
                      >&ensp;元
                    </el-form-item>
                    <el-form-item
                      v-if="
                        scope.$index >= planFormData.allocationPlan.length - 1
                      "
                      style="margin-bottom: 0"
                      label-width="0"
                    >
                      <el-input
                        v-model="calcCost"
                        title="本栏根据应拨付总额自动计算"
                        disabled="true"
                        style="width: 240px"
                        class="table-input"
                      ></el-input
                      >&ensp;元
                    </el-form-item>
                  </template>
                </el-table-column>
                <div slot="empty" v-show="isEmpty">
                  <emptyTable emptyText="暂无相关信息" />
                </div>
              </el-table>
            </div>
          </el-row>
          <!-- 黄石定制需求 -->
          <el-row
            class="detailInfoItemSty"
            v-if="userType == 'MONITOR' && isHsUser()"
          >
            <el-row class="detailInfoItemSty">
              <span class="gridContent color333 fontSizeF" style="width: 100px"
                >应拨付总额：</span
              >
              <span class="gridContent empContentSty color333 fontSizeF">
                {{
                  planFormData.total
                }}元&ensp;（如监察修改拨付计划金额，应拨付总额将自动跟随修改）
              </span>
            </el-row>
          </el-row>
          <!-- 黄石定制需求 -->
          <el-row class="detailInfoItemSty">
            <el-form-item label="合同附件：" prop="uploadFile">
              <uploadAnnex
                :upLoadFile="planFormData.uploadFile"
                :limitationFactor="limitationFactorLicense"
                @getFile="getFileLicense"
              />
              <!-- <div class="uploadBox">
                <el-button round class="uploadImg">上传</el-button>
                <p class="uploadImgState">请上传施工合同中关于工资性工程款的约定拨付内容部分，在系统中备案。</p>
                <p class="uploadImgState">仅支持png，jpg，jpeg格式的图片，大小2MB</p>
                <div class="upLoadDom">
                  <form id="contractFileForm">
                    <input type="file" id="contractFile" name="file" @change="fileChange()" />
                  </form>
                </div>
              </div> -->
            </el-form-item>
            <el-row>
              <el-col :span="24">
                <uploadResult
                  :resultList="planFormData.uploadFile"
                  @callBackResult="getFileLicense"
                  style="margin-left: 100px !important"
                />
                <!-- <elementImage :upLoadFile="planFormData.uploadFile"   :srcList="planFormData.srcList" :oldSrcList="planFormData.oldSrcList"  @changeSrcList="changeSrcList"></elementImage> -->
              </el-col>
            </el-row>
          </el-row>
        </el-row>
        <div class="separator"></div>
      </el-form>
      <el-row type="flex" justify="center" style="padding-top: 24px">
        <el-button
          type="primary"
          @click.native="saveAllocationPlan('planForm')"
          class="btn save"
          :loading="saveLoading"
          >保存</el-button
        >
        <el-button @click.native="goBack" class="btn cancel">返回</el-button>
      </el-row>
    </div>
  </div>
</template>

<script>
import common from '../../kits/common'
import filterMethods from '@/kits/filterMethod.js'
export default {
  name: 'setAllocationPlan',

  data() {
    var checkTotal = (rule, value, callback) => {
      var reg = /^(([1-9]\d*)(\.\d{1,2})?|0\.([1-9]|\d[1-9])|0)$/
      if (!reg.test(value)) {
        return callback(new Error('请输入整数或两位小数'))
      } else {
        return callback()
      }
    }
    var checkUpLoadFile = (rule, value, callback) => {
      // var that = this;
      if (this.planFormData.uploadFile.length == 0) {
        return callback(new Error('工资性工程款拨付合同附件不能为空'))
      } else {
        callback()
      }
    }
    var checkHasSeted = async (rule, value, callback) => {
      // var that = this;
      // await this.getHasSeted(this.planFormData.projectId);
      if (this.hasSeted) {
        if (this.isClick) {
          this.$message({
            message: '该项目已创建过拨付计划',
            type: 'error',
          })
        }
        return callback(new Error('该项目已创建过拨付计划'))
      } else if (!this.hasAccount) {
        return callback(new Error(this.tips))
      } else {
        callback()
      }
    }
    var checkCurrentCost = (rule, value, callback) => {
      // var that = this;
      let sum = 0
      for (let i = 0; i < this.planFormData.allocationPlan.length - 1; i++) {
        sum += this.planFormData.allocationPlan[i].shouldDisburseTotal * 1
      }
      // this.planFormData.allocationPlan.forEach((v) => {
      //   sum += v.shouldDisburseTotal * 1;
      // });
      var reg = /^(([1-9]\d*)(\.\d{1,2})?|0\.([1-9]|\d[1-9])|0)$/
      if (this.isHsUser() && this.userType == 'MONITOR') {
        if (!reg.test(value)) {
          return callback(new Error('请输入整数或两位小数'))
        } else if (value <= 0) {
          return callback(new Error('本期拨付金额应大于0'))
        } else {
          return callback()
        }
      } else {
        if (!reg.test(value)) {
          return callback(new Error('请输入整数或两位小数'))
        } else if (value > this.planFormData.total * 1) {
          return callback(new Error('本期拨付金额大于应拨付总额'))
        } else if (value <= 0) {
          return callback(new Error('本期拨付金额应大于0'))
        } else if (sum > this.planFormData.total * 1) {
          this.isTotalMuch = true
          return callback(new Error('累计拨付金额大于应拨付总额'))
        } else {
          return callback()
        }
      }
    }
    var debounceCheck = (rule, vlaue, callback) => {
      let sum = 0
      for (let i = 0; i < this.planFormData.allocationPlan.length - 1; i++) {
        sum += this.planFormData.allocationPlan[i].shouldDisburseTotal * 1
      }
      // this.planFormData.allocationPlan.forEach((v) => {
      //   sum += v.shouldDisburseTotal * 1;
      // });
      if (sum > this.planFormData.total * 1 && this.isClick) {
        this.$message({
          message: '累计应拨付金额大于应拨付总额，请修改',
          type: 'error',
        })
      }
      return callback()
    }
    return {
      id: '', //修改拨付计划id
      isClick: false, //点击toast
      isTotalMuch: false,
      calcCost: '',
      loginType: '', //角色bulider施工方
      payPlanType: '', //MANUAL_NEED_AUDIT需审核生效
      actionType: '', //操作类型
      projectList: [], //项目列表
      hasSeted: false, //是否已经创建过拨付计划
      hasAccount: true, //是否有专户
      projectDetail: {}, //项目详情
      isEmpty: false,
      planFormData: {
        projectId: '',
        // type: "",
        total: '',
        allocationTime: '',
        allocationPlan: [], //拨付计划周期
        uploadFile: [], //附件文件列表
        oldSrcList: [], //预览地址
        srcList: [],
      },
      rules: {
        projectId: [
          { required: true, message: '请选择项目', trigger: 'change' },
          {
            required: true,
            validator: checkHasSeted,
            trigger: 'change',
          },
        ],
        total: [
          { required: true, message: '请输入应拨付总额', trigger: 'blur' },
          { validator: checkTotal, trigger: 'blur' },
        ],
        allocationTime: [
          { required: true, message: '请选择拨付时间', trigger: 'change' },
        ],
        shouldDisburseTotal: [
          { required: true, message: '请输入本期应拨付金额', trigger: 'blur' },
          {
            required: true,
            validator: checkCurrentCost,
            trigger: 'blur',
          },
          // {
          //   required: true,
          //   validator: this.debounce(debounceCheck, 1000),
          //   trigger: "blur",
          // },
        ],
        uploadFile: [
          {
            required: true,
            validator: checkUpLoadFile,
            trigger: 'blur',
          },
        ],
      },
      isLoading: false, //表格按钮
      saveLoading: false, //保存按钮
      isShowSave: '',
      tips: '', //页面提示
      userType: '',
      totalPayable: '', //黄石监察计算应拨付总额
      limitationFactorLicense: {
        uploadAnnexUrl: 'api-f/files/upload', //自定义上传文件接口地址
        upLoadFileLength: 10, //自定义上传附件的个数设置
        fileSize: 5, //自定义上传文件最大设置
        formatType: 'typeOne', //自定义上传格式校验类型
        fileId: 'license', //自定义id解决一个页面包含多个上传附件
        uploadFormId: 'licenseForm', //自定义id解决一个页面包含多个上传附件
        messagetip: '要求格式为png，jpg，jpeg格式，附件大小不超过2MB', //自定义报错提示语
        methodTip:
          '请上传施工合同中关于工资性工程款的约定拨付内容部分，在系统中备案。仅支持png，jpg，jpeg格式的图片，大小2MB', //自定义上传文件提示
        uploadBtnType: 'typeOne', //自定义上传按钮类型
      },
    }
  },
  async created() {
    this.disbursesetup()
    this.userType = this.$store.state.userType
    if (this.$store.state.userType === 'COMPANY') {
      if (localStorage.getItem('judgeRoleCode') == 'constructor') {
        this.loginType = 'bulider' //施工方
      } else if (localStorage.getItem('judgeRoleCode') == 'owner') {
        this.loginType = 'constructor' //建设方
      }
    }
    // this.isShowSave =
    //   this.$store.state.buttonLimitsArr.indexOf("accountList:update") > -1;
    //从其他页面跳创建计划默认tab为专户列表
    this.$store.commit(
      'set_active_index',
      '/home/specialAccount/specialAccountList'
    )
    this.$store.state.activeMenu = '/home/specialAccount/specialAccountList'
    this.actionType = this.$route.query.type
    if (this.userType != 'MONITOR') {
      await this.getProjectList() //获取项目列表
    }
    if (this.$route.query.type === 'add') {
      this.getAllocationCircle('first')
    } else if (this.$route.query.type === 'update') {
      this.id = this.$route.query.id
      await this.getAllocaionDetail(this.id) //获取拨付计划详情
      await this.getDisbursePlanDetail(this.id) //获取拨付周期详情
    }
  },
  methods: {
    //获取拨付生成方式系统配置
    disbursesetup() {
      this.axios({
        method: 'get',
        url: 'api-acc/cs/disbursesetup/expand/get',
      })
        .then((response) => {
          this.payPlanType = response.data.result
        })
        .catch((error) => {
          this.$message.error('数据获取失败')
        })
    },
    // 计算最后一个拨付周期的值
    async checkLastCost(formName, type) {
      // 前端计算失精度
      // let sum = 0;
      // for (let i = 0; i < this.planFormData.allocationPlan.length - 1; i++) {
      //   sum += Number((this.planFormData.allocationPlan[i].shouldDisburseTotal * 100).toFixed(0));
      // }
      // this.calcCost = this.planFormData.allocationPlan[
      //   this.planFormData.allocationPlan.length - 1
      // ].shouldDisburseTotal = ((this.planFormData.total*100 - sum)/100).toFixed(2);
      // this.$refs.planForm.validateField("shouldDisburseTotal", (valid) => {});
      if (type == 'hs') {
        await this.hsCalcLastCost()
      } else {
        await this.calcLastCost()
      }
      this.$refs[formName].validate((valid) => {})
      this.$refs[formName].clearValidate([
        'projectId',
        'total',
        'allocationTime',
        'uploadFile',
      ])
    },
    // 计算最后一个值
    calcLastCost() {
      let costArr = []
      for (let i = 0; i < this.planFormData.allocationPlan.length - 1; i++) {
        costArr.push(
          this.planFormData.allocationPlan[i].shouldDisburseTotal + ''
        )
      }
      let str = this.planFormData.total + ''
      let currentMoney = 0
      if (str && str != 'null') {
        currentMoney = str.split(',').join('')
      } else {
        currentMoney = 0
      }
      return this.axios({
        method: 'post',
        url: 'api-bs/base/subtract',
        data: {
          sub: currentMoney,
          minus: JSON.stringify(costArr),
        },
      })
        .then((response) => {
          this.calcCost = this.planFormData.allocationPlan[
            this.planFormData.allocationPlan.length - 1
          ].shouldDisburseTotal = response.data.result
        })
        .catch((error) => {
          this.$message({
            message: '获取本期应拨付额失败',
            type: 'error',
          })
        })
    },
    // 黄石定制需求最后一个值可编辑，计算应拨付总额
    hsCalcLastCost() {
      let costArr = []
      for (let i = 0; i < this.planFormData.allocationPlan.length; i++) {
        costArr.push(
          this.planFormData.allocationPlan[i].shouldDisburseTotal + ''
        )
      }
      return this.axios({
        method: 'post',
        url: 'api-bs/base/subtract',
        data: {
          minus: JSON.stringify(costArr),
        },
      })
        .then((response) => {
          this.planFormData.total = response.data.result
        })
        .catch((error) => {
          this.$message({
            message: '获取本期应拨付额失败',
            type: 'error',
          })
        })
    },
    // 获取项目列表
    getProjectList() {
      return new Promise((resolve, reject) => {
        this.axios({
          method: 'post',
          url: 'api-p/projectcompany/expand/current/projects',
        })
          .then((response) => {
            resolve(response)
            this.projectList = response.data.result
          })
          .catch((error) => {
            reject(error)
            this.$message({
              message: '获取项目列表失败',
              type: 'error',
            })
          })
      })
    },
    // 获取项目详情
    async getProjectDetail(id) {
      this.hasSeted = false
      this.planFormData.allocationTime = ''
      await this.getProjectInfo(id)
      this.getAllocationCircle('first')
      this.$refs.planForm.validateField('projectId', (valid) => {})
    },
    // 获取项目信息
    getProjectInfo(id) {
      return new Promise((resolve, reject) => {
        this.axios({
          method: 'post',
          url: 'api-acc/cs/disburseaudit/expand/accountinfo',
          data: {
            projectId: id,
          },
        })
          .then((res) => {
            if (res.data.hasError) {
              this.hasAccount = false
              this.projectDetail = {}
              this.planFormData.allocationPlan = []
              this.planFormData.allocationTime = ''
              this.planFormData.total = ''
              this.planFormData.uploadFile = []
              this.planFormData.srcList = []
              this.planFormData.oldSrcList = []
              this.tips = res.data.errorMsg
            } else {
              this.hasAccount = true
              if (res.data.result.hasCreatedDisbursePlan) {
                this.hasSeted = res.data.result.hasCreatedDisbursePlan
                this.projectDetail = {}
                this.planFormData.allocationPlan = []
                this.planFormData.allocationTime = ''
                this.planFormData.total = ''
                this.planFormData.uploadFile = []
                this.planFormData.srcList = []
                this.planFormData.oldSrcList = []
              } else {
                this.hasSeted = false
                this.projectDetail = res.data.result
                this.planFormData.total =
                  '' || this.projectDetail.shouldDisburseTotal
                this.calcLastCost()
              }
            }
            resolve(res)
          })
          .catch((error) => {
            reject(error)
            this.$message({
              showClose: true,
              message: '获取项目详情失败',
              type: 'error',
            })
          })
      })
    },

    // 修改获取拨付计划详情
    getAllocaionDetail(id) {
      return new Promise((resolve, reject) => {
        this.axios({
          method: 'post',
          url: 'api-acc/cs/disburseaudit/expand/updatefindDisbursePlan',
          data: {
            disbursePlanId: id,
          },
        })
          .then((res) => {
            resolve(res)
            let projectDetail = res.data.result
            this.projectDetail = JSON.parse(JSON.stringify(projectDetail))
            this.projectDetail.leader = projectDetail.managerName
            this.projectDetail.leaderTel = projectDetail.managerTel

            this.planFormData.projectId = projectDetail.projectId
            this.planFormData.allocationTime = projectDetail.disburseTime
            this.planFormData.total = filterMethods.splitNumber(
              projectDetail.shouldDisburseTotal
            )
            this.planFormData.uploadFile = projectDetail.disbursePlanFiles
            this.planFormData.srcList = this.planFormData.uploadFile.map(
              (v) => {
                return v.url
              }
            )
            this.planFormData.oldSrcList = JSON.parse(
              JSON.stringify(this.planFormData.srcList)
            )
            if (this.isHsUser() && this.userType == 'MONITOR') {
              var obj = {}
              for (var key in this.projectDetail) {
                if (key == 'projectName' || key == 'projectId') {
                  obj = {
                    code: this.projectDetail['projectId'],
                    name: this.projectDetail['projectName'],
                  }
                }
              }
              this.projectList.push(obj)
            }
          })
          .catch((error) => {
            reject(error)
            this.$message({
              showClose: true,
              duration: 3000,
              message: '获取拨付计划详情数据失败',
              type: 'error',
            })
          })
      })
    },
    // 修改获取拨付周期详情
    getDisbursePlanDetail(id) {
      return new Promise((resolve, reject) => {
        this.axios({
          method: 'post',
          url: 'api-acc/cs/disburseaudit/expand/updatefindDisbursePlanDetail',
          data: {
            disbursePlanId: id,
          },
        })
          .then((res) => {
            resolve(res)
            let details = res.data.result
            let allocationPlan = []
            details.forEach((v, i) => {
              allocationPlan[i] = {}
              allocationPlan[i].startDate = v.startDate.split('.').join('-')
              allocationPlan[i].endDate = v.endDate.split('.').join('-')
              allocationPlan[i].shouldDisburseTotal = v.shouldDisburseTotal
              allocationPlan[i].id = v.id
            })
            this.planFormData.allocationPlan = JSON.parse(
              JSON.stringify(allocationPlan)
            )
            this.calcCost = details[details.length - 1].shouldDisburseTotal
          })
          .catch((error) => {
            reject(error)
            this.$message({
              showClose: true,
              duration: 3000,
              message: '获取拨付计划周期详情失败',
              type: 'error',
            })
          })
      })
    },
    // 获取拨付周期时间
    getAllocationCircle(type, date) {
      if (this.projectDetail.startDate && this.projectDetail.endDate) {
        const dateArr = this.dataMonth(
          this.projectDetail.startDate,
          this.projectDetail.endDate,
          date
        )
        let planArr = []
        if (type === 'first') {
          dateArr.forEach((v, i) => {
            // this.planFormData.allocationPlan[i] = {};
            // this.planFormData.allocationPlan[i].startTime = v[0];
            // this.planFormData.allocationPlan[i].endTime = v[1];
            // this.planFormData.allocationPlan[i].shouldDisburseTotal = null;
            planArr[i] = {}
            planArr[i].startDate = v[0]
            planArr[i].endDate = v[1]
            planArr[i].shouldDisburseTotal = null
          })
        } else {
          planArr = JSON.parse(JSON.stringify(this.planFormData.allocationPlan))
          dateArr.forEach((v, i) => {
            // planArr[i] = {};
            planArr[i].startDate = v[0]
            planArr[i].endDate = v[1]
            planArr[i].shouldDisburseTotal =
              this.planFormData.allocationPlan[i].shouldDisburseTotal
          })
        }
        this.planFormData.allocationPlan = JSON.parse(JSON.stringify(planArr))
      } else {
        this.isEmpty = true
      }
    },
    //保存计划设置
    saveAllocationPlan(formName) {
      this.isClick = true
      //确定按钮禁止点击
      this.saveLoading = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isHsUser() && this.userType == 'MONITOR') {
            this.planFormData.allocationPlan = this.planFormData.allocationPlan
          } else {
            this.planFormData.allocationPlan[
              this.planFormData.allocationPlan.length - 1
            ].shouldDisburseTotal = this.calcCost
          }

          var url = ''
          this.isClick = false
          let data = {}
          data.disbursePlanFile = JSON.stringify(this.planFormData.uploadFile)
          let str = this.planFormData.total + ''
          let currentMoney = 0
          if (str) {
            currentMoney = str.split(',').join('')
          }
          data.shouldDisburseTotal = currentMoney
          data.disburseTime = this.planFormData.allocationTime
          if (this.actionType === 'add') {
            url = 'api-acc/cs/disburseaudit/expand/createplan'
            data.accountId = this.projectDetail.id
            data.projectId = this.planFormData.projectId
            // type= this.planFormData.type;
            data.details = JSON.stringify(this.planFormData.allocationPlan) //拨付周期
          } else {
            url = 'api-acc/cs/disburseaudit/expand/updateSaveDisbursePlan'
            data.id = this.id
            data.detail = JSON.stringify(this.planFormData.allocationPlan)
          }
          this.savePlanAjax(url, data)
        } else {
          this.debounceTotal()
          // this.debounce(this.debounceTotal, 1000);
          this.isTotalMuch = false
          this.saveLoading = false
          this.isClick = false
          return false
        }
      })
    },
    //保存计划ajax
    savePlanAjax(url, data) {
      this.axios({
        method: 'post',
        url: url,
        data: data,
      })
        .then((res) => {
          if (!res.data.hasError) {
            this.saveLoading = false
            this.$message({
              message: '保存成功',
              type: 'success',
            })
            this.$router.push({
              path: '/home/specialAccount/specialAccountList',
            })
            this.$store.commit('CHANGE_SLIDER_NAME', {
              oldUrl: '/home/specialAccount/specialAccountList',
              newUrl: this.$router.currentRoute.fullPath,
            })
          } else {
            this.$message({
              message: res.data.errorMsg,
              type: 'error',
            })
          }
        })
        .catch((error) => {
          this.saveLoading = false
          this.$message({
            message: '保存失败',
            type: 'error',
          })
        })
    },
    goBack() {
      this.$router.push('/home/specialAccount/specialAccountList')
      this.$store.commit('GOBACK_NAME', {
        oldUrl: '/home/specialAccount/specialAccountList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    //合同图片上传
    fileChange(type) {
      var Filedata
      var file
      var fileSize
      Filedata = $('#contractFile').val()
      if (!Filedata) {
        return
      }
      try {
        file = $('#contractFile')[0].files[0]
        fileSize = (file.size / 1024).toFixed(0)
      } catch (e) {
        this.$message({
          message:
            '您的浏览器暂不支持计算上传文件的大小，确保上传文件不要超过5M，建议使用FireFox、Chrome或IE10以上浏览器。',
          type: 'warning',
        })
      }
      // 文件大小和限制类型可以通过子组件传值区分，若不适应于使用页面，可自行判断
      if (this.planFormData.uploadFile.length == 20) {
        this.$message({
          message: '最多上传20个附件',
          type: 'warning',
        })
        $('#contractFile').val('')
        return
      }
      if (fileSize / 1 > 1024 * 2) {
        this.$message({
          message: '最多能上传2M以内的图片',
          type: 'warning',
        })
        return
      }
      if (!/\.(png|jpg|jpeg|PNG|JPG|JPEG)$/.test(Filedata)) {
        this.$message({
          message: '仅支持上传png、jpg、jpeg格式文件',
          type: 'warning',
        })
        return
      }
      let that = this
      var options = {
        url: common.uploadUrl + 'api-f/files/upload',
        type: 'POST',
        dataType: 'json',
        success: function (data) {
          that.planFormData.uploadFile.push(data)
          that.planFormData.srcList.push(data.url)
          that.planFormData.oldSrcList.push(data.url)
          $('#contractFile').val('')
          that.$refs.planForm.validateField('uploadFile', (valid) => {})
        },
        error: function () {},
      }
      $('#contractFileForm').ajaxSubmit(options)
      return false
    },

    /**
     * @description: 改变图片地址
     */
    changeSrcList(val) {
      this.planFormData.srcList = val
    },
    // 获取周期数组
    dataMonth(value1, value2, day) {
      var getDate = function (str) {
        var tempDate = new Date()
        var list = str.split('-')
        tempDate.setFullYear(list[0] * 1)
        tempDate.setDate(1)
        tempDate.setMonth(list[1] * 1 - 1)
        tempDate.setDate(list[2] * 1)
        return tempDate
      }
      var date1 = getDate(value1)
      var date2 = getDate(value2)
      var dateArr = new Array()
      var i = 0
      dateArr[i] = new Array()
      if (!day) {
        dateArr[i] = [value1, 0]
        i++
      } else {
        dateArr[i][0] = value1
      }
      date1.setDate(1)
      date1.setMonth(date1.getMonth() + 1)
      while (
        !(
          date1.getFullYear() > date2.getFullYear() ||
          (date1.getFullYear() == date2.getFullYear() &&
            date1.getMonth() > date2.getMonth())
        )
      ) {
        let lastDay = getLastDay(date1.getFullYear(), date1.getMonth() + 1)
        if (!day) {
          dateArr[i] = [
            date1.getFullYear() +
              '-' +
              ((date1.getMonth() + 1).toString().length == 1
                ? '0' + (date1.getMonth() + 1)
                : date1.getMonth() + 1) +
              '-0' +
              1,
            0,
          ]
        } else {
          dateArr[i + 1] = new Array()
          let currentDay =
            date1.getFullYear() +
            '-' +
            ((date1.getMonth() + 1).toString().length == 1
              ? '0' + (date1.getMonth() + 1)
              : date1.getMonth() + 1) +
            '-' +
            ((day * 1).toString().length == 1 ? '0' + day : day)
          if (day * 1 > lastDay * 1) {
            currentDay =
              date1.getFullYear() +
              '-' +
              ((date1.getMonth() + 1).toString().length == 1
                ? '0' + (date1.getMonth() + 1)
                : date1.getMonth() + 1) +
              '-' +
              lastDay
          }
          dateArr[i][1] = currentDay
          let next = getDate(currentDay)
          let nextDay = nextDate(next)
          dateArr[i + 1][0] = nextDay
        }
        i++
        // date1.setDate(date1.getDate() + 1);
        date1.setMonth(date1.getMonth() + 1)
      }
      if (day) {
        let lastDay = getLastDay(date1.getFullYear(), date1.getMonth() + 1)
        let currentDay =
          date1.getFullYear() +
          '-' +
          ((date1.getMonth() + 1).toString().length == 1
            ? '0' + (date1.getMonth() + 1)
            : date1.getMonth() + 1) +
          '-' +
          ((day * 1).toString().length == 1 ? '0' + day : day)
        if (day * 1 > lastDay * 1) {
          currentDay =
            date1.getFullYear() +
            '-' +
            ((date1.getMonth() + 1).toString().length == 1
              ? '0' + (date1.getMonth() + 1)
              : date1.getMonth() + 1) +
            '-' +
            lastDay
        }
        dateArr[i][1] = currentDay
      }
      return dateArr
      // 获取指定日期下一天
      function nextDate(date) {
        date = new Date(date)
        date = +date + 1000 * 60 * 60 * 24
        date = new Date(date)
        return (
          date.getFullYear() +
          '-' +
          ((date.getMonth() + 1).toString().length == 1
            ? '0' + (date.getMonth() + 1)
            : date.getMonth() + 1) +
          '-' +
          (date.getDate().toString().length == 1
            ? '0' + date.getDate()
            : date.getDate())
        )
      }
      // 获取指定年份最后一天
      function getLastDay(year, month) {
        var new_year = year //取当前的年份
        var new_month = month++ //取下一个月的第一天，方便计算（最后一天不固定）
        if (month > 12) {
          new_month -= 12 //月份减
          new_year++ //年份增
        }
        var new_date = new Date(new_year, new_month, 1) //取当年当月中的第一天
        return new Date(new_date.getTime() - 1000 * 60 * 60 * 24).getDate() //获取当月最后一天日期
      }
    },
    // 转换日期格式
    changeFormat(v) {
      if (v) {
        const time = new Date(v)
        return (
          time.getFullYear() +
          '.' +
          (time.getMonth() + 1).toString().padStart(2, 0) +
          '.' +
          time.getDate().toString().padStart(2, 0) +
          ' ' +
          time.getHours().toString().padStart(2, 0) +
          ':' +
          time.getMinutes().toString().padStart(2, 0) +
          ':' +
          time.getSeconds().toString().padStart(2, 0)
        )
      } else {
        return '无'
      }
    },
    debounceTotal() {
      if (this.isTotalMuch) {
        this.$message({
          message: '累计应拨付金额大于应拨付总额，请修改',
          type: 'error',
        })
      }
    },
    // toast提示防抖
    debounce(func, wait) {
      let timer
      let that = this
      return function (that) {
        let context = that // 注意 this 指向
        let args = arguments // arguments中存着e

        if (timer) clearTimeout(timer)

        timer = setTimeout(() => {
          func.apply(context, args)
        }, wait)
      }
    },
    getFileLicense(val) {
      this.planFormData.uploadFile = val
    },
    // debounce(fn, delay) {
    //   // 记录上一次的延时器
    //   var timer = null;
    //   var delay = delay || 500;
    //   return function () {
    //     var args = arguments;
    //     var that = this;
    //     // 清除上一次延时器
    //     clearTimeout(timer);
    //     timer = setTimeout(function () {
    //       fn.apply(that, args);
    //     }, delay);
    //   };
    // },
  },
}
</script>

<style lang="less" scoped>
@media screen and (min-width: 1280px) and (max-width: 1366px) {
  .searchInputWidth /deep/ .el-form-item__label {
    width: 82px;
  }
}
.form-item {
  width: 300px;
}
/deep/ .el-dialog__body {
  padding: 0;
}
/deep/ .el-dialog__title {
  font-size: 18px;
  color: #424242;
}
/deep/ .el-select {
  width: 340px;
}
/deep/ .el-form-item__label {
  color: #333333;
}

.topTitle {
  height: 67px;
  background-color: #e4ebf1;
  padding-left: 24px;
  font: bold 18px/67px Microsoft YaHei;
  .titleStyle {
    color: #333;
    font-size: 22px;
  }
}
.mainCon {
  // padding-left: 24px;
  //   padding-right: 24px;
  height: calc(100% - 67px);
  overflow-y: auto;
  padding: 0 !important;
}

.stateBox {
  padding: 20px 24px;
  //  border-bottom: 10px solid #f5f7fa;
}

.planProgress {
  border-bottom: 10px solid #f5f7fa;
}
.examineStatus {
  // margin-top: 24px;
  // margin-bottom:24px;

  padding: 20px 30px;
  font-size: 18px;
  color: #333333;
  font-weight: bold;
  background: #f8f9fb;
  //
  .planStatus i {
    vertical-align: middle;
  }
  .iconfont {
    font-size: 22px;
  }
  .pass {
    color: #009588;
  }
  .pending {
    color: #ffac37;
  }
  .rejected {
    color: #d81e06;
  }
  .cancelling {
    color: #3d5266;
  }
  .cancelled {
    color: #3d5266;
  }
  .rejectedReason {
    font-size: 14px;
    color: #333333;
    font-weight: 400;
    padding-left: 33px;
    margin-top: 10px;
  }
}
.contentInfo {
  //   margin-top: 24px;
  margin: 24px;
  font-size: 0;
  .group-title {
    position: relative;
    padding-left: 20px;
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: bold;
    // &::before {
    //   position: absolute;
    //   content: "";
    //   width: 4px;
    //   height: 24px;
    //   left: 0;
    //   top: 12px;
    //   background: #265FAA;
    // }
  }
  // .subTitle {
  //   text-align: right;
  //   font-size: 14px;
  //   color: #333333;
  //   text-align: right;
  //   line-height: 36px;
  //   display: inline-block;
  //   width: 120px;
  // }
  // .subContent {
  //   font-size: 14px;
  //   color: #666666;
  //   text-align: left;
  //   line-height: 36px;
  // }

  .allocationDetail {
    font-size: 14px;
    color: #333333;
  }
}
// .textInfo {
//   font-size: 0;
// }
// .labelWidth {
//   display: inline-block;
//   height: 36px;
//   position: relative;
// }
// .labelWidth::before {
//   content: "";
//   display: block;
//   position: absolute;
//   top: 20px;
//   left: -10px;
//   width: 5px;
//   height: 5px;
//   background: #009588;
//   border-radius: 50%;
// }
.imgStyle {
  margin-left: 12px;
  li {
    position: relative;
    margin-right: 20px;
    margin-bottom: 20px;
    .iconjian {
      position: absolute;
      right: -6px;
      top: -10px;
      font-size: 20px;
      cursor: pointer;
    }
    .el-image {
      cursor: pointer;
    }
  }
}
.reminderBox {
  height: 38px;
  margin-bottom: 24px;
  padding: 0 24px;
  text-align: center;
  margin-top: 24px;
  ul {
    font-size: 0;
    height: 38px;
    display: inline-block;
    // margin-bottom: 20px;
    li {
      // display: inline-block;
      // &:nth-child(even) {
      //   width: 316px;
      // }
      float: left;
      padding: 0 10px;
      height: 100%;
      position: relative;

      width: 110px;
      text-align: left;
      .circle {
        display: inline-block;
        text-align: center;
        background: #3c3d49;
        color: #fff;
        height: 22px;
        line-height: 22px;
        width: 22px;
        font-size: 14px;
        border-radius: 50%;
        margin-right: 10px;
        position: absolute;
        top: 8px;
        left: 8px;
      }
      .titleInfo {
        position: absolute;
        left: 40px;
        top: 50%;
        -webkit-transform: translateY(-50%);
        transform: translateY(-50%);
        font-size: 14px;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
    }
    li:nth-of-type(1) {
      width: 200px;
    }
    li:nth-of-type(5) {
      width: 280px;
    }
  }
}
.arrowRight {
  text-align: center;
  line-height: 100%;
  width: 20%;
  background: url('./../../../static/img/icon1.png') center repeat-x;
  margin: 0 16px;
}
.arrowRight img {
  vertical-align: middle;
  height: 14px;
  width: 10px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -7px;
  margin-left: -5px;
}
.uploadBox {
  position: relative;
  .uploadImg {
    width: 96px;
    height: 40px;
    color: #009588;
    border: 1px solid #009588;
    cursor: pointer;
  }
  .upLoadDom {
    position: absolute;
    width: 96px;
    height: 40px;
    top: 0;
    left: 0;
    opacity: 0;
    line-height: 0px;
    form {
      input {
        width: 96px;
        height: 40px;
        line-height: 0px;
        cursor: pointer;
      }
    }
  }
  .uploadImgState {
    font-size: 14px;
    color: #adadad;
    line-height: 14px;
    margin-top: 10px;
  }
}
.imgStyle {
  margin-left: 100px;
  margin-top: 10px;
  li {
    position: relative;
    margin-right: 20px;
    margin-bottom: 20px;
    .iconjian {
      position: absolute;
      right: -6px;
      top: -10px;
      font-size: 20px;
      cursor: pointer;
    }
    .el-image {
      cursor: pointer;
    }
  }
}
.btn {
  width: 120px;
  line-height: 36px !important;
  height: 36px !important;
}
/deep/.el-table--border td,
/deep/ .el-table--border th {
  border-right: none;
  // height: 80px;
}
/deep/.el-table td {
  padding: 0;
}

.rightBox {
  width: 88px;
  display: inline-block;
  text-align: right;
}
// /deep/ .el-table_1_column_2 {
//   text-align: center;
// }
.detailInfoItemSty32 {
  margin-top: 32px;
}

/deep/.el-table td > .cell {
  padding: 18px 16px;
}
</style>
